<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/28
 * 营销模块
 * Time: 14:54
 */

namespace app\common\model\market;

use app\common\model\TimeModel;


class MarketItem extends TimeModel
{
    protected $deleteTime = 'delete_time';

    /**图片获取器
     * @param $value
     * @return string
     */
    public function setImageAttr($value){

        return implode(',',$value);
    }

    public function getImageAttr($value){
        return explode(',',$value);
    }

    public function getContentAttr($value){
        return htmlspecialchars_decode($value);
    }

    //商品所属分类
    public function category()
    {
        return $this->belongsTo('app\common\model\common\Categories','category_id','id')->field('id,name');
    }

    //商品所属商家
    public function store()
    {
        return $this->belongsTo('app\common\model\mall\Store','store_id','id')->field('id,name');
    }

    //商品下所有的sku
    public function ItemSku()
    {
        return $this->hasMany('app\common\model\market\MarketItemSku','market_id','id');
    }
    //商品下所有的ItemSkuSpec
    public function ItemSkuSpec()
    {
        return $this->hasMany('app\common\model\mall\ItemSkuSpec','goods_id','item_id');
    }

    //获取所属秒杀时间段
    public function SeckillTime()
    {
        return $this->belongsToMany('app\common\model\market\SeckillTime','relation_seckill','time_id','other_id');

    }
    /**
     * 新增后置操作
     */
    public static function onAfterInsert($data)
    {

        $relation_seckill = app('app\common\model\market\RelationSeckill');

        $relation_seckill->save(['other_id'=>$data['id'],'app_id'=>self::get_appId(),'time_id'=>$data['time_id']]);
    }

    /**
     * 更新后置操作
     */
    public static function onAfterUpdate($data)
    {

        $relation_seckill = app('app\common\model\market\RelationSeckill');
        $res = $relation_seckill->where(['other_id'=>$data['id'],'time_id'=>$data['time_id']]);
        $res && $res->delete();
        $relation_seckill->save(['other_id'=>$data['id'],'time_id'=>$data['time_id']]);
    }
}